package simplescenegraph.math;

import java.util.Iterator;
import java.util.LinkedList;

public class VertexBuffer3f implements Iterable<Vertex3f> {

	private LinkedList<Vertex3f> list = new LinkedList<Vertex3f>();

	float[] staticBuffer = null;

	public void preppend(Vertex3f v0) {
		list.addFirst(v0);
		staticBuffer = null;
	}

	public void append(Vertex3f v0) {
		list.add(v0);
		staticBuffer = null;
	}

	public int size() {
		return list.size();
	}

	public float[] toFloatArray() {
		if (staticBuffer == null) {
			staticBuffer = new float[list.size() * 8];
		}

		int c = 0;
		Vector3f position; 
		Vector3f normal;
		Vector2f uvCoordinate;
		for (Vertex3f vertex : list) {
			position = vertex.getPosition();
			normal = vertex.getNormal();
			uvCoordinate = vertex.getUVCoordinate();
			
			staticBuffer[c++] = position.x;
			staticBuffer[c++] = position.y;
			staticBuffer[c++] = position.z;
			staticBuffer[c++] = normal.x;
			staticBuffer[c++] = normal.y;
			staticBuffer[c++] = normal.z;
			staticBuffer[c++] = uvCoordinate.x;
			staticBuffer[c++] = uvCoordinate.y;
		}

		return staticBuffer;
	}

	public Iterator<Vertex3f> iterator() {
		return list.iterator();
	}

	public Vertex3f get(int i) {
		return list.get(i);
	}

	public void setAllNormalsTo(Vector3f normal) {
		if (normal == null) {
			throw new IllegalArgumentException();
		}
		
		for (Vertex3f vertex : list) {
			vertex.setNormal(normal);
		}
	}

}
